#ifndef __GPIB_H__
#define __GPIB_H__

#include "care.h"

#define GPIB_S_DAT	1
#define GPIB_R_DAT	2
#define GPIB_R_SRQ	3
#define RD_AD_CMD 	4
#define SET_IO_CMD 	5
#define RESET_CMD   6

//#define TIMEOUT 160
#define WAIT 		1

#define true 1
#define false 0

#define FLAGS_AUTO	1			// True if instrument sets to talk after command
#define FLAGS_EOI	2			// True in case we should set EOI on last char of command
#define FLAGS_EOT_ENABLE	4	// True in case we should add an EOT char after EOI
#define FLAGS_MODE	8			// True if we are controller
#define FLAGS_LON	16			// True if we are in listen only mode

//
// GPIB receive finite-state-machine states
//
#define GPIB_RX_START						0
#define GPIB_RX_ACCEPT					1
#define GPIB_RX_WAIT_DAV 				2
#define GPIB_RX_DAV_LOW					3
#define GPIB_RX_WAIT_DAV_HIGH 	4
#define GPIB_RX_DAV_HIGH 				5
#define GPIB_RX_EOI							6
#define GPIB_RX_FINISH 					9
#define GPIB_RX_DAV_TIMEOUT			10
#define GPIB_RX_DONE 						99

//
// GPIB send finite-state-machine states
//
#define GPIB_TX_START					0
#define GPIB_TX_CHECK					1
#define GPIB_TX_PUT_DATA			2
#define GPIB_TX_WAIT_FOR_NRFD	3
#define GPIB_TX_SET_DAV_LOW		4
#define GPIB_TX_WAIT_FOR_NDAC	5
#define GPIB_TX_SET_DAV_HIGH	6
#define GPIB_TX_FINISH 				9
#define GPIB_TX_ERROR 				98
#define GPIB_TX_DONE 					99


#define GPIB_MAX_TX_LEN			64		// Max length of transmit GPIB string
#define GPIB_MAX_RX_LEN			256		// Max length of receive GPIB string
#define GPIB_MAX_CMD_LEN		32		// Max length of GPIB incoming command


#define CMD_DCL 0x14
#define CMD_UNL 0x3f
#define CMD_UNT 0x5f
#define CMD_GET 0x8
#define CMD_SDC 0x04
#define CMD_LLO 0x11
#define CMD_GTL 0x1
#define CMD_SPE 0x18
#define CMD_SPD 0x19


#define LISTEN 	0x20
#define TALK 		0x40


void care_GPIB_init(void);

rt_uint8_t care_protocol(rt_uint8_t device,char *bytes, rt_uint8_t length);

rt_uint8_t 	_gpib_write(char *bytes, rt_uint8_t length, rt_bool_t cmd, rt_bool_t use_eoi);
rt_uint8_t 	gpib_write(char *bytes, rt_uint8_t length, rt_bool_t use_eoi);
rt_uint8_t 	gpib_cmd(char *bytes, rt_uint8_t length);

rt_uint32_t gpib_read(rt_uint8_t use_eoi, rt_uint8_t eos_code, rt_uint8_t eot_enable, rt_uint8_t eot_char);
rt_uint32_t gpib_read_byte(char *byte, rt_uint8_t *eoi_status);

void gpib_ren(rt_uint8_t state);
void gpib_ifc(void);

rt_uint8_t GPIB_puts(rt_uint8_t str);
rt_uint8_t GPIB_gets(void);

rt_uint8_t address_target_talk(rt_uint8_t address);
rt_uint8_t address_target_listen(rt_uint8_t address);
rt_uint8_t send_gpib_unlisten(rt_uint8_t address);

void serial_poll(rt_uint8_t address) ;
void return_care(char *source_bytes,char *bytes, rt_uint8_t length);
rt_uint8_t care_protocol_state(void);

rt_int8_t readln(char *byte);
rt_uint16_t StrHex(char *str);
void offline_collect(void);
rt_int8_t offline_writeln(char *byte,rt_uint8_t len);

#endif


